package com.lemon.es.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lemon.es.service.EsService;
import com.lemon.es.web.Page;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李猛
 * @datetime 2024/2/22 15:48
 * @description 类对象
 */
@Slf4j
@Service
public class EsServiceImpl implements EsService {
    @Resource
    private RestHighLevelClient client;

    @Override
    public void add(String index, Object data) {
        //插入数据
        IndexRequest request = new IndexRequest();

        //插入数据，必须转换为 JSON 格式
        String jsonStr = JSONUtil.toJsonStr(data);

        //获取ID
        Object id = JSONUtil.toBean(jsonStr, JSONObject.class).get("id");
        request.index(index).id(id == null ? IdUtil.getSnowflakeNextIdStr() : id.toString());

        request.source(jsonStr, XContentType.JSON);

        try {
            //响应结果
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("~~~~~~~~~~~~~EsServiceImpl.add~~~~~~~~~~~~");
            e.printStackTrace();
        }
    }

    @Override
    public <T> T getById(String index, String id, Class<T> tClass) {
        //查询数据
        GetRequest request = new GetRequest();
        request.index(index).id(id);

        try {
            //响应结果
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            String source = response.getSourceAsString();
            return JSONUtil.toBean(source, tClass);
        } catch (IOException e) {
            log.error("~~~~~~~~~~~~~EsServiceImpl.getById~~~~~~~~~~~~");
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public <T> Page<T> page(String index, SearchSourceBuilder query, Class<T> tClass) {
        //全量查询
        SearchRequest request = new SearchRequest();
        request.indices(index);

        //查询条件
        request.source(query);

        //分页结果集
        Page<T> result = new Page<>();

        //数据记录
        List<T> records = new ArrayList<>();
        try {
            //搜索结果集
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            response.getHits().forEach(item -> {
                JSONObject obj = JSONUtil.toBean(item.getSourceAsString(), JSONObject.class);
                obj.putOpt("id", item.getId());
                records.add(JSONUtil.toBean(obj, tClass));
            });

            //数据总条数
            result.setTotal(response.getHits().getTotalHits().value);
        } catch (IOException e) {
            log.error("~~~~~~~~~~~~~EsServiceImpl.page~~~~~~~~~~~~");
            e.printStackTrace();
        }

        result.setRecords(records);
        return result;
    }

    @Override
    public void delById(String index, String id) {
        //删除数据
        DeleteRequest request = new DeleteRequest();
        request.index(index).id(id);

        //响应结果
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("~~~~~~~~~~~~~EsServiceImpl.delById~~~~~~~~~~~~");
            e.printStackTrace();
        }
    }

    @Override
    public boolean createIndex(String index) {
        //创建索引
        CreateIndexRequest request = new CreateIndexRequest(index);
        try {
            //RequestOptions.DEFAULT 默认的请求配置
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            return response.isAcknowledged();
        } catch (IOException e) {
            log.error("~~~~~~~~~~~~~EsServiceImpl.createIndex~~~~~~~~~~~~");
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteIndex(String index) {
        //删除索引
        DeleteIndexRequest request = new DeleteIndexRequest(index);

        try {
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            return response.isAcknowledged();
        } catch (IOException e) {
            log.error("~~~~~~~~~~~~~ElasticsearchServiceImpl.deleteIndex~~~~~~~~~~~~");
            e.printStackTrace();
            return false;
        }
    }
}
